package com.three.crm.tencentcloud;

import android.content.Context;
import android.text.TextUtils;

import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.three.crm.util.LogUtils;
import com.three.crm.util.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class CosServiceUtils {

    private TransferManager mTransferManager;
    private UpLoadCallBack mUpLoadCallBack;//自己定义一个接口接收返回的东西

    public CosServiceUtils(TransferManager mtransferManager) {
        this.mTransferManager = mtransferManager;
    }

    public void setUpLoadCallBack(UpLoadCallBack upLoadCallBack){
        this.mUpLoadCallBack = upLoadCallBack;
    }

    public void uploadFile(Context context,String filePath,String fileName,String fileType,UpLoadCallBack callBack){
        File file = new File(filePath);
        String cosPath = getCosFile(fileType);
        if(TextUtils.isEmpty(fileName)){
            cosPath += file.getName();
        } else {
            cosPath += fileName;
        }
        /**
         * 上传时的本地和 COS 路径
         */
        String currentUploadPath = filePath;
        LogUtils.onUploadLog("文件路径：" + currentUploadPath);
        COSXMLUploadTask cosxmlTask = mTransferManager.upload(BaseConfig.BUCKET, cosPath,currentUploadPath, null);
        LogUtils.onUploadLog("文件上传cosxmlTask：" + cosxmlTask.toString());
        cosxmlTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(final long complete, final long target) {
                LogUtils.onUploadLog("文件上传过程，已完成：" + complete + ",总共：" + target);
                callBack.onProgress(complete,target);
            }
        });

        cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                LogUtils.onUploadLog("文件上传成功：" + result.accessUrl);
                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                callBack.onSuccess(cOSXMLUploadTaskResult.accessUrl);
            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                if (exception != null) {
                    exception.printStackTrace();
                }
                if (serviceException != null) {
                    serviceException.printStackTrace();
                }
                LogUtils.onUploadLog("文件上传失败：" + exception.getMessage() + serviceException.getErrorMessage());
                ToastUtils.showToast(exception.toString() + "," + serviceException.getErrorMessage());
                callBack.onFail();
            }
        });
        cosxmlTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(final TransferState state) {
                LogUtils.onUploadLog("文件上传发生变化：" + state.toString());
                if (state.toString().equals("FAILED")) {
                    ToastUtils.showToast("上传失败！");
                }
                callBack.onStatusChange(state);
            }
        });
    }

    public static void onUploadFile(Context context,String secretId, String secretKey,String sessionToken
            ,long startTime,long expiredTime, boolean refresh,String filePath,String fileName,String fileType,UpLoadCallBack callBack){
        CosXmlService mCosXmlService = CosServiceFactory.getCosXmlService(context,secretId,secretKey,sessionToken,startTime,expiredTime,refresh);
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        TransferManager transferManager = new TransferManager(mCosXmlService,transferConfig);
        File file = new File(filePath);
        String cosPath = getCosFile(fileType);
        if(TextUtils.isEmpty(fileName)){
            cosPath += file.getName();
        } else {
            cosPath += fileName;
        }
        /**
         * 上传时的本地和 COS 路径
         */
        String currentUploadPath = filePath;
        COSXMLUploadTask cosxmlTask = transferManager.upload(BaseConfig.BUCKET, cosPath,currentUploadPath, null);
        cosxmlTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(final TransferState state) {
                callBack.onStatusChange(state);
            }
        });
        cosxmlTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(final long complete, final long target) {
                callBack.onProgress(complete,target);
            }
        });

        cosxmlTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                COSXMLUploadTask.COSXMLUploadTaskResult cOSXMLUploadTaskResult = (COSXMLUploadTask.COSXMLUploadTaskResult) result;
                callBack.onSuccess(cOSXMLUploadTaskResult.accessUrl);
            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                if (exception != null) {
                    exception.printStackTrace();
                }
                if (serviceException != null) {
                    serviceException.printStackTrace();
                }
                callBack.onFail();
            }
        });
    }

    public static String getCosFile(String type){
        String res = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        if (type.contains("video")) {
            res = "video/";
        } else {
            res = "cover/";
        }
        return res + dateFormat.format(calendar.getTime()) + "/" + minute + second + "_";
    }

    public interface UpLoadCallBack{
        void onProgress(long complete, long target);
        void onStatusChange(TransferState state);
        void onSuccess(String url);
        void onFail();
    }
}
